import axios, { AxiosError, type AxiosInstance, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'

class HttpRequest {
  service!: AxiosInstance

  init(baseURL: string) {
    this.service = axios.create({
      baseURL,
      timeout: 30 * 1000,
      headers: {}
    })

    // request interceptor
    this.service.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        return config
      },
      (error: AxiosError) => {
        return Promise.reject(error)
      }
    )

    // response interceptor
    this.service.interceptors.response.use(
      (response: AxiosResponse) => {
        // 检查配置的响应类型是否为二进制类型（'blob' 或 'arraybuffer'）, 如果是，直接返回响应对象
        if (response.config.responseType === 'blob' || response.config.responseType === 'arraybuffer') {
          return response
        }

        const res = response.data
        if (res.code && res.code !== 200) {
          ElMessage.error(res.errMessage || '系统异常,请联系管理员')
          return Promise.reject(new Error(res.errMessage || '系统异常,请联系管理员', { cause: 'axios' }))
        } else {
          return res
        }
      },
      (error: any) => {
        let { message } = error
        if (message === 'Network Error') {
          message = '后端接口连接异常'
        } else if (message.includes('timeout')) {
          message = '系统接口请求超时'
        } else if (message.includes('Request failed with status code')) {
          message = '系统接口' + message.substr(message.length - 3) + '异常'
        }
        return Promise.reject(error)
      }
    )

    return this.service
  }
}

export default new HttpRequest()
